<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { getConnectionList } from '@/api/connection'
  import { createTask, editTask } from '@/api/task'

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const id = ref();

  const formSchema: FormSchema[] = [
  {
      field: 'connection_id',
      label: '互联方',
      component: 'ApiSelect',
      componentProps: {
        api: getConnectionList,
        params: {},
        resultField: 'items',
        labelField: 'partner.name',
        valueField: 'id',
        immediate: true,
      },
    },
    {
      field: 'name',
      label: '名称',
      required: true,
      component: 'Input',
    },
    {
      field: 'task',
      label: '函数',
      required: false,
      component: 'Input',
    },
    {
      field: 'crontab.minute',
      label: '分',
      required: true,
      component: 'Input',
    },
    {
      field: 'crontab.hour',
      label: '时',
      required: true,
      component: 'Input',
    },
    {
      field: 'crontab.day_of_week',
      label: '每周的第几天',
      required: true,
      component: 'Input',
    },
    {
      field: 'crontab.day_of_month',
      label: '每月的第几天',
      required: true,
      component: 'Input',
    },
    {
      field: 'crontab.month_of_year',
      label: '每年的第几月',
      required: true,
      component: 'Input',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    isUpdate.value = data?.isUpdate;
    id.value = data?.record?.id;
    resetFields();
    setDrawerProps({ confirmLoading: false });
    if (unref(isUpdate)) {
      setFieldsValue({
        connection_id: data.record.connection?.id,
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增任务' : '编辑任务'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });

      if (unref(isUpdate)) {
        await editTask(id.value, values);
      } else {
        await createTask(values);
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>